package com.boxing.filter;

import com.boxing.bean.User;
import com.boxing.utils.WebUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter" ,urlPatterns = {"/login/*", "*.jsp"})
public class LoginFilter implements Filter {
    private static Logger LOG = LogManager.getLogger();

    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest requestS, ServletResponse responseS, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) requestS;
        HttpServletResponse response = (HttpServletResponse) responseS;

        // 校验 现在收到的cookie 跟 登录成功后响应给浏览器的cookie 是否一致
        String token = (String) WebUtil.findCookie(request, "token");
        // 从 session 中取出之前存储的 token
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("token");
        String srcToken = "";
        if (user != null){
            srcToken = user.getToken();
        }
        String requestUrl = request.getRequestURL().toString();
        if (token == null || !token.equals(srcToken)){
            if (!requestUrl.contains("login.jsp") && !requestUrl.contains("regist.jsp")){
                System.out.println("跳转到登录页面 srcToken " + srcToken +" 请求地址:"+requestUrl);
                response.sendRedirect(request.getContextPath()+"/login.jsp");
            }
        }else {
            // 已登陆
            LOG.debug(requestUrl + " 已校验状态  已登录");
        }
        chain.doFilter(request, response);
    }
}
